package fr.nts.framework.front.form.validation.validator;

import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

import fr.nts.framework.front.form.validation.FieldValidationResult;
import fr.nts.framework.front.form.validation.annotation.StringConstraint;

/**
 * Définit les règles pour valider un nombre d'un formulaire NTS
 * 
 * @author sco
 * @version 1.0.0
 */
@Component("stringValidator")
public class StringValidator implements Validator<StringConstraint>{
	 
	private static final String MAX_SIZE_EMPTY_ERROR_CODE = "string.constraint.max.size";
	private static final String MIN_SIZE_EMPTY_ERROR_CODE = "string.constraint.min.size";
	private static final String REG_EX_EMPTY_ERROR_CODE = "string.constraint.regex";
	private static final String NOT_NULL_CODE = "string.constraint.not.null";
	 
	/*
	 * (non-Javadoc)
	 * @see fr.nts.framework.front.form.validation.Validator#valid(java.lang.Object, java.lang.Object)
	 */
	@Override
	public FieldValidationResult valid(final String[] formValues, 
			                           final StringConstraint rules){
		
		// Liste globale des erreurs
		Map<String,List<String>> errorsMap = Maps.newHashMap();
		
		// Pour chaque champ à tester
		for(String value: formValues){
			List<String> errors = Lists.newArrayList();
			
			// Règle not null
			if(rules.notNull() && StringUtils.isEmpty(value)){
				errors.add(NOT_NULL_CODE);
			}
			
			// Règle min size
			if(rules.minSize() >= 0){
				if(value == null || (value.length() < rules.minSize())){
					errors.add(MIN_SIZE_EMPTY_ERROR_CODE);
				}
			}
			
			
			// Règle max size
			if(rules.maxSize() >= 0){
				if(value != null){
					if(value.length() > rules.maxSize()){
						errors.add(MAX_SIZE_EMPTY_ERROR_CODE);
					}
				}
			}
			
			
			// Règle Reg ex
			if(!StringUtils.isEmpty(rules.regEx())){
				if(value == null || !value.matches(rules.regEx())){
					errors.add(REG_EX_EMPTY_ERROR_CODE);
				}
			}
			
			if(!errors.isEmpty()){
				errorsMap.put(value, 
					          errors);
			}
		}
		
		// Résultat final
		if(!errorsMap.isEmpty()){
			return new FieldValidationResult(errorsMap);
		}else{
			return FieldValidationResult.ok;
		}
	}
}